package com.jessefyz.module.controller.shop;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jessefyz.aspectj.CurrentMember;
import com.jessefyz.common.core.controller.BaseController;
import com.jessefyz.common.core.domain.AjaxResult;
import com.jessefyz.common.core.page.TableDataInfo;
import com.jessefyz.common.exception.DataNotFoundException;
import com.jessefyz.module.member.domain.MemberInfo;
import com.jessefyz.module.shop.constants.OrderConstants;
import com.jessefyz.module.shop.domain.Aftersale;
import com.jessefyz.module.shop.domain.LitemallOrder;
import com.jessefyz.module.shop.domain.LitemallOrderGoods;
import com.jessefyz.module.shop.domain.req.AftersaleAdd;
import com.jessefyz.module.shop.domain.req.AftersaleReq;
import com.jessefyz.module.shop.domain.vo.AftersaleVo;
import com.jessefyz.module.shop.service.IAftersaleService;
import com.jessefyz.module.shop.service.ILitemallOrderGoodsService;
import com.jessefyz.module.shop.service.ILitemallOrderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 售后服务
 *
 * 目前只支持订单整体售后，不支持订单商品单个售后
 *
 * 一个订单只能有一个售后记录
 */
@RestController
@RequestMapping("/wx/aftersale")
@Validated
public class WxAftersaleController extends BaseController {
    private final Log logger = LogFactory.getLog(WxAftersaleController.class);

    @Autowired
    private IAftersaleService aftersaleService;
    @Autowired
    private ILitemallOrderService orderService;
    @Autowired
    private ILitemallOrderGoodsService orderGoodsService;

    /**
     * 售后列表
     * @return 售后列表
     */
    @GetMapping("list")
    public TableDataInfo<AftersaleVo> list(@ApiIgnore @CurrentMember MemberInfo currentMember,
                                           AftersaleReq aftersaleReq){
        startPage();
        QueryWrapper<Aftersale> lqw = new QueryWrapper<Aftersale>();
        aftersaleReq.generatorQuery(lqw,true);
        List<AftersaleVo> list = aftersaleService.listVo(lqw);
        for (AftersaleVo aftersale : list) {
            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.list(new LambdaQueryWrapper<LitemallOrderGoods>()
                    .eq(LitemallOrderGoods::getOrderId,aftersale.getOrderId())
            );
            aftersale.setOrderGoodsList(orderGoodsList);
        }
        return getDataTable(list);

    }

    /**
     * 售后详情
     *
     * @param orderId 订单ID
     * @return 售后详情
     */
    @GetMapping("detail/{orderId}")
    public Object detail(@ApiIgnore @CurrentMember MemberInfo currentMember, @PathVariable Long orderId) {
        LitemallOrder order = Optional.ofNullable(orderService.getOne(new LambdaQueryWrapper<LitemallOrder>()
                .eq(LitemallOrder::getId,orderId)
                .eq(LitemallOrder::getUserId,currentMember.getId())
        ,false)).orElseThrow(()-> new DataNotFoundException("订单不存在"));

        order.setOrderHandleOption(OrderConstants.build(order));
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.list(new LambdaQueryWrapper<LitemallOrderGoods>()
            .eq(LitemallOrderGoods::getOrderId,orderId)
        );
        order.setGoodsVoList(orderGoodsList);
        Aftersale aftersale = aftersaleService.getOne(new LambdaQueryWrapper<Aftersale>()
                .eq(Aftersale::getOrderId,orderId)
                .eq(Aftersale::getUserId,currentMember.getId())
        ,false);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("aftersale", aftersale);
        data.put("order", order);
        return AjaxResult.success(data);
    }

    /**
     * 申请售后
     * @return 操作结果
     */
    @PostMapping("submit")
    public AjaxResult submit(@ApiIgnore @CurrentMember MemberInfo currentMember,@Valid @RequestBody AftersaleAdd aftersaleAdd) {
        Aftersale aftersale = Convert.convert(new TypeReference<Aftersale>() {}, aftersaleAdd);
        aftersale.setUserId(currentMember.getId());
        return toAjax(this.aftersaleService.saveAftersale(aftersale) ? 1 : 0);
    }

    /**
     * 取消售后
     * 如果管理员还没有审核，用户可以取消自己的售后申请
     * @return 操作结果
     */
    @PostMapping("cancel/{id}")
    public Object cancel(@ApiIgnore @CurrentMember MemberInfo currentMember, @PathVariable Long id) {
        return toAjax(this.aftersaleService.cancel(currentMember.getId(),id) ? 1 : 0);
    }
}
